<?php
/**
 * @file   Index.php
 * @date   2019-02-27 14:49:36
 * @author huwhis<huuwhois>
 * @version   0.0.1
 */
namespace app\blog\controller;

use think\Controller;
use think\Request;
use app\admin\model\BlogCategory;
use app\admin\model\BlogArticle;
use app\admin\model\BlogGuestBook;

class Index extends Controller
{
    protected $article_model;

    public function __construct()
    {
        parent::__construct();

        $categories = BlogCategory::getCategories();
        $this->assign('categories', $categories);

        $this->article_model = new BlogArticle();
    }

    public function index()
    {
        // PHP      
        $php_data = $this->article_model->getLists(1, 1, 7);
        $this->assign('php_data', $php_data['lists']);
        // 学习笔记
        $notes_data = $this->article_model->getLists(2, 1, 7);
        $this->assign('notes_data', $notes_data['lists']);
        
        // PHP 学习笔记 杂项Top文章
        $php_top = $this->article_model->getTopOne(1);
        $notes_top = $this->article_model->getTopOne(2);
        $other_top = $this->article_model->getTopOne(3);
        $this->assign('php_top', $php_top);
        $this->assign('notes_top', $notes_top);
        $this->assign('other_top', $other_top);
        

        $all_data = $this->article_model->getLists(0, 1, 9);
        $this->assign('lists', $all_data['lists']);
        
        $this->aside();
        return $this->fetch();
    }

    /**
     * 侧边栏
     */
    public function aside()
    {
        $catedata = BlogCategory::getCategories(['template'=>1]);
        $clicks_data = $this->article_model->getLists(0, 1, 7, 0, 1, [], '', 'clicks desc');
        $top_data = $this->article_model->getLists(0, 1, 7, 1);

        $this->assign('cate_lists', $catedata);
        $this->assign('clicks_lists', $clicks_data['lists']);
        $this->assign('top_lists', $top_data['lists']);
    }

    /**
     * 文章列表
     */
    public function lists($cid = null, $page = 1)
    {
        $data = $this->article_model->getLists($cid, $page, 15);

        $this->assign('data', $data);
        $this->assign('cid', $cid);
        $this->assign('page', $page);
        
        $this->aside();
        return $this->fetch();
    }

    /**
     * 阅读文章
     */
    public function read($id=null)
    {
        $data = $this->article_model->getOne($id);

        if (!$data) {
            throw new \think\exception\HttpException(404, '页面不存在');
        }

        $prev_next = $this->getNextPrev($id, $data->cid);
        $this->assign('cid', $data->cid);
        $this->assign('data', $data);
        $this->assign('prev_next', $prev_next);
        
        $this->aside();
        return $this->fetch();
    }
    
    public function getNextPrev($id, $cid = null)
    {
        if ($cid) {
            $id_list = $this->article_model->where(['status' => 1, 'isdel' => 0, 'cid' => $cid])
                ->order(['sort' => 'desc', 'id' => 'desc'])
                ->column('id');
        } else {
            $id_list = $this->article_model->where(['status' => 1, 'isdel' => 0])->column('id');
        }

        if (count($id_list)==1) {
            $data_p = null;
            $data_N = null;
        } else {
            $key = array_search($id, $id_list);
            if ($key == 0) {
                $data_p = null;
                $N = $id_list[1];
                $data_N = $this->article_model->field('id,title,pubtime')->find($N);
            } elseif ($key == count($id_list) - 1) {
                $P = $id_list[count($id_list) - 2];
                $data_p = $this->article_model->field('id,title,pubtime')->find($P);
                $data_N = null;
            } else {
                $P = $id_list[$key - 1];
                $data_p = $this->article_model->field('id,title,pubtime')->find($P);
                $N = $id_list[$key + 1];
                $data_N = $this->article_model->field('id,title,pubtime')->find($N);
            }
        }

        return ['prev' => $data_p, 'next' => $data_N];
    }

    /**
     * 文章点赞
     */
    public function getLike()
    {
        $id = input('post.id');

        $like = $this->article_model->where('id', $id)->value('like');
        $like = $like + 1;
        $res = $this->article_model->save(['like'=>$like], ['id'=>$id]);

        if ($res===false) {
            return ['code' => 0];
        } else {
            return ['code' => 2];
        }
    }

    /**
     * 时光轴
     */
    public function time($page = 1)
    {
        $order=['pubtime' => 'desc'];

        $data = $this->article_model->getLists(0, $page, 15, 0, 1, [], '', $order);

        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }
    
    public function article($year = 0, $month = 0, $day = 0, $id = 0)
    {
        
        $data = $this->article_model->getOne($id);
        if (!$data) {
            throw new \think\exception\HttpException(404, '页面不存在');
        } else {
            $this->assign('data', $data);
        }

        $cid = $data->cid;
        $this->assign('cid', $cid);

        $prev_next = $this->getNextPrev($id);
        $this->assign('prev_next', $prev_next);

        $this->aside();
        return $this->fetch();
    }

    /**
     * 关于&留言
     */
    public function about()
    {
        return $this->fetch();
    }

    public function guestBook()
    {
        $data = BlogGuestBook::getGuestBooks();
        $this->assign('data', $data);

        return $this->fetch();
    }
    
    public function saveGuestBook(Request $request = null)
    {
        $param = $request->param();

        if (empty($param['author']) or empty($param['email'])) {
            $this->assign('data', ['msg'=>"请填写必填字段（姓名，电子邮件）", 'code'=>1]);
            return $this->fetch('error');
        }

        if (empty($param['comment'])) {
            $this->assign('data', ['msg'=>"请留下内容", 'code'=>1]);

            return $this->fetch('error');
        }

        array_pop($param);

        try {
            $bgu = new BlogGuestBook();
            $res = $bgu->save([
                'comment' => $param['comment'],
                'author' => $param['author'],
                'email' => $param['email'],
                'url' => $param['url'],
                'time' => time(),
            ]);
        } catch (\Exception $e) {
            $msg = $e->getMessage();

            $this->assign('data', ['msg'=>$msg, 'code'=>1]);
            return $this->fetch('error');
        }

        $this->redirect(url('blog/index/guestbook'), 302);
    }
}
